package com.suhe.ozon;

import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;

import java.io.FileOutputStream;
import java.io.IOException;

/**
 * <p>
 * </p>
 *
 * @author liuning
 * @date 10:28 2024/3/26
 */
public class Pdf3 {
    public static void main(String[] args) {
        try {
            // 读取PDF文档
            PdfReader reader = new PdfReader("/Users/ningdd/Downloads/4b648e08-b18e-413e-8567-4d9a37331d5b.pdf");
            int numPages = reader.getNumberOfPages();

            // 创建输出流
            PdfStamper stamper = new PdfStamper(reader, new FileOutputStream("/Users/ningdd/Downloads/1.pdf"));

            // 遍历每一页
            for (int i = 1; i <= numPages; i++) {
                // 获取页面内容
                PdfDictionary page = reader.getPageN(i);
                PdfObject content = page.getDirectObject(PdfName.CONTENTS);

                // 替换文字内容
                if (content instanceof PRStream) {
                    PRStream stream = (PRStream) content;
                    byte[] data = PdfReader.getStreamBytes(stream);
                    String contentString = new String(data, "UTF-8");
                    contentString = contentString.replaceAll("礼品套装", "玩具");
                    stream.setData(contentString.getBytes("UTF-8"));
                }
            }

            // 关闭流
            stamper.close();
            reader.close();

            System.out.println("文字替换完成！");
        } catch (IOException | DocumentException e) {
            e.printStackTrace();
        }
    }
}
